package org.cfk.delaytasktutorial.example;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.cfk.delaytasktutorial.annotation.LazyJob;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class OrderTimeoutTask {

    public static final String WORKER_NAME = "order_timeout_task";

    @Data
    public static class OrderTimeoutParam {
        private String orderId;
        private String userId;
        private Double amount;
        private String status; // PENDING, PAID, CANCELLED等
    }

    @LazyJob(WORKER_NAME)
    public void cancelOrder(OrderTimeoutParam param) {
        log.info("开始处理超时订单，订单ID：{}，用户：{}，金额：{}",
                param.getOrderId(), param.getUserId(), param.getAmount());
        
        try {
            // 这里模拟订单取消的具体实现
            // 1. 检查订单状态
            if (!"PENDING".equals(param.getStatus())) {
                log.info("订单{}已不处于待支付状态，无需取消", param.getOrderId());
                return;
            }
            
            // 2. 执行订单取消逻辑
            Thread.sleep(200); // 模拟数据库操作延迟
            log.info("订单{}已取消，释放库存", param.getOrderId());
            
            // 3. 发送取消通知
            Thread.sleep(100); // 模拟发送通知延迟
            log.info("已发送订单取消通知给用户：{}", param.getUserId());
            
        } catch (InterruptedException e) {
            log.error("订单取消失败：{}", param.getOrderId(), e);
            Thread.currentThread().interrupt();
            throw new RuntimeException("取消订单失败", e);
        }
    }
}